package java8.list;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class IteratorRemoveDemo {

    private static List<String> list = new ArrayList<>();

    static {
        list.add("list1");
        list.add("list2");
        list.add("list3");
    }


    public static void remove1(){
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).equals("list2")){
                list.remove(i);
            }
        }


    }

    public static void remove2(){
        Iterator<String> iterator = list.iterator();

        while (iterator.hasNext()){
            String row = iterator.next();

            if(row.equals("list2")){
                iterator.remove();
                list.add("list4");
            }

        }
    }

    public static void remove3(){
        Iterator<String> iterator = list.iterator();

        while (iterator.hasNext()){
            String row = iterator.next();

            if(row.equals("list2")){
                list.add("list2");
            }

        }
    }

    //在创建迭代器之后，除非通过迭代器自身的 remove 或 add 方法从结构上对列表进行修改，否则在任何时间以任何方式对列表进行修改，迭代器都会抛出 ConcurrentModificationException
    public static void removeAndAdd1(){
        //Exception in thread "main" java.util.ConcurrentModificationException
        Iterator<String> iterator = list.iterator();

        while (iterator.hasNext()){
            String row = iterator.next();

            if(row.equals("list2")){
                iterator.remove();
                list.add("list4");
            }

        }
    }

    public static void removeAndAdd2(){
        ListIterator<String> iterator = list.listIterator();

        while (iterator.hasNext()){
            String row = iterator.next();

            if(row.equals("list2")){
                iterator.remove();
                iterator.add("list4");
            }

        }
    }


    public static void main(String[] args) {
        remove3();

        System.out.print("集合：\n\t"+list+"\n");

    }
}
